#! /usr/bin/env python
#coding=utf-8

from twisted.internet import protocol
from twisted.protocols import basic
from twisted.internet import reactor
from JsonCode import JsonCode
from SwitchDB import SwitchDB


class ServerListen(basic.LineReceiver):

    def __init__(self):
        self.rec = ''
        self.f = ""
        self.i = 0
        self.Error = "APP_SQL_Error for json "
    
    def dataReceived(self, data):
        jc = JsonCode()

        if data[0] != "{":
            d = data.split('\n')
            data = d[-1]
            
        djs = jc.DECode(data)
        #print '---- jsoncode ---'
        swdb = SwitchDB()
        res = swdb.SWDoing(djs)
        
        ejs = jc.EnCode(res)
        if ejs != None:            
            m=0
            step = 65530
            s = ejs[m:m+step]

            while len(s)>0:
                self.transport.write(s)
                m += step
                s = ejs[m:m+step]
        else:
            self.transport.write("")
        self.transport.loseConnection()

    def connectionMade(self):
        pass
    
    def connectionLost(self, reason):
        self.transport.loseConnection()

class ConfigServerFactory(protocol.ServerFactory):
    protocol = ServerListen
    clients = []
    
class DoingListen:
    
    def __init__(self, host, port):

        reactor.listenTCP(port,ConfigServerFactory())
        reactor.run()        
